import React, { useEffect, useState,useRef } from 'react'
import Content from './components/content/Content'
import Option from './components/option/Option'
import axios from 'axios'

const App = () => {
  const [content,setContent] = useState([])
  const qusetionRef = useRef(null)
  const wrapRef = useRef(null)
  const [total,setTotal] = useState(null) 

  const getExam = async() => {
    const res = await axios.get('https://zyxcl.xyz/exam_api/exan_data')
    // console.log(res.data)
    setContent(res.data)
  }

  useEffect(() => {
    getExam()
  },[])
  // 跳转到哪一题
  const onJump = (index) => {
    console.log(index)
    console.log(qusetionRef.current.children[index])
    wrapRef.current.scrollTop = qusetionRef.current.children[index].offsetTop
  }
  // 设置有没有这个答案
  const changeAnswer = (index,answer) => {
    // console.log(index,answer)
    const newContents = [...content]
    newContents[index].answer = answer
    setContent(newContents)
  }

// 提交
const onSubmit = () => {
  // console.log(content)
  const newContent = [...content]
  let t = 0
  newContent.forEach(item => {
    if(item.answer === item.result) {
      t += item.score
    }else {
      item.isError = true
    }
  })
  // const t = content.reduce((prev,val) => {
  //   return prev + (val.answer === val.result? val.score : 0 )
  // },0)
  setContent(newContent)
  setTotal(t)
}

const isFinish = total !== null

  return (
    <div className='box'>
      <div className='wrap' ref={wrapRef}>
        <div className='content' ref={qusetionRef}>
          {content.map((item,index) => 
              <Content 
              key={index} {...item} 
              no={index + 1}
              index={index}
              isFinish={isFinish}
              onChange={changeAnswer}
              />
            )}
        </div>
      </div>
      <Option 
      list={content} 
      onJump={onJump} 
      onSubmit={onSubmit}
      isFinish={isFinish}
      total={total}
      />
    </div>
  )
}

export default App